#!/usr/bin/env python2
# -*- conding: utf-8 -*-


import functools
import traceback
from Ump.common import log

job_log = log.get_logger('Schedule')


def load_global_flask_app():
    mod = __import__('Ump.schedule.main', globals(), locals(), ['']) 
    app = getattr(mod, '_app')
    return app 


def log_info_run(exc_handler=None):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kw):
            try:
                job_name = self.__class__.__name__
                app = load_global_flask_app()
                with app.app_context():
                    res = func(self, *args, **kw)
                    job_log.info("%s job run success" % (job_name))
                return res
            except Exception, e:
                print e, '=================================='
                traceback.print_exc()
                job_log.error("%s job run error: %s" % (job_name, traceback.format_exc()))
                if exc_handler:
                    exc_handler(e, *args, **kw)
                else:
                    raise
        return wrapper
    return decorator


